package xyz.xtt.exchange.service.impl;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import xyz.xtt.exchange.service.IUploadService;
import xyz.xtt.exchange.utils.CosFileUtil;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Service
@Slf4j
public class UploadServiceImpl implements IUploadService {

    @Autowired
    private CosFileUtil cosFileUtil;

    /**
     * 上传oss key
     **/
    private static final String key = "/image/";
    private static final String protocolPre = "https://cdn-nft-sandbox.xtt.xyz";
    private static final Pattern FILE_EXTENSION_PATTERN = Pattern.compile("(?<=\\.)[^.]+$");

    @Override
    public String upload(MultipartFile file) {
        File fi = null;
        try {
            fi = covertToFile(file);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        String path = uploadFileToOxx(fi);

        log.info("图片上传oss完整路径为：{}", protocolPre + path);
        return protocolPre + path;
    }

    /**
     * 上传图片至服务器
     *
     * @param file
     * @return String
     * @author xugaopeng
     * @date 2024/12/12 14:53
     **/
    private String uploadFileToOxx(File file) {
        return cosFileUtil.uploadFileToCos(file, key);
    }


    private File covertToFile(MultipartFile file) throws IOException {
        Matcher matcher = FILE_EXTENSION_PATTERN.matcher(file.getOriginalFilename());
        String suffix = "";
        if (matcher.find()) {
            suffix = matcher.group().toLowerCase();
        }
        FileOutputStream fos = null;
        try {
            File tempFile = File.createTempFile("prefix-", "." + suffix);
            fos = new FileOutputStream(tempFile);
            // 将MultipartFile的内容写入临时文件
            fos.write(file.getBytes());
            return tempFile;
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            if (fos != null) {
                fos.close();
            }
        }
    }
}
